<template>
  <view class="wrapper" :style="specialStyle" @touchstart="$emit('closeBubble');">
    <view class="majorFilterContainer">
      <!-- <scroll-view :scroll-x="true" class="firstListContainer" scroll-with-animation
        :scroll-into-view='scollFirstToView'>
        <view v-for="item,index in majorFirstList" :key="index"
          :class="{'firstListItem':true, 'selectedFirst':item.positionTagId==selectedFirstId}" :id="`first-${index}`"
          @click="handleFirstItemClick(item,index)">
          {{item.tagName}}
        </view>
      </scroll-view> -->

      <!-- 第一层 -->
      <view class="firstListContainer">
        <u-tabs :list="majorFirstList" bg-color='transparent' :height="100" inactive-color="#222" active-color="#222"
          :bar-style="{display:'none'}" name="navName" is-scroll="true" :current="selectedFirstIndex"
          @change="handleFirstItemClick" :gutter='28' :active-item-style="tabActiveStyle">
        </u-tabs>
      </view>

      <!-- 推荐内容 -->
      <scroll-view v-if="selectedFirstIndex == 0" scroll-y scroll-with-animation class="recommendArea"
        :style="{ height: scrollViewHeight + 'px' }">
        <view class="recommendItem" v-for="item,index in recommend" :key="index" @click="handleThirdItemClick(item)">
          <view class="recommendImgArea">
            <img class="recommendImg" :src="item.pic" alt="">
          </view>
          <view class="recommendText">{{ item.positionName }}</view>
        </view>
      </scroll-view>

      <!-- 第二、三级 -->
      <view v-else class="mainListContainer">
        <scroll-view :scroll-y="true" :scroll-top='scrollSecondTop' scroll-with-animation class="secondPositionList"
          :style="{ height: scrollViewHeight + 'px' }">
          <view :class="{'SecondPositionItem':true,'u-line-2':true, 'selectedSecond':(item.navId==selectedSecondId)}"
            v-for="item,index in secondPositionList" :key="index" @click="handleSecondItemClick(item,index)">
            <span v-if="item.navName=='热门'" class="hotSecondPosition"> <img
                src="https://img3.job1001.com/ypMp/elan/images/career/hotSecondPosition.png"> {{item.tagName}}</span>
            <span v-else>{{item.navName}}</span>
          </view>
        </scroll-view>
        <scroll-view :scroll-y="true" scroll-with-animation class="thirdPositionList"
          :scroll-into-view='scollThirdToView' @scroll.native="handleScroll" ref="scollView"
          :style="{ height: scrollViewHeight + 'px' }">
          <view class="ThirdPositionItem" v-for="item,index in secondPositionList" :key="index">
            <view :class="{'thirdTitle':true,fixedTitle:item.isFixTitle}">
              <template v-if="item.navName=='热门'"> {{item.navName}} <text
                  class="titleTip">大家都在搜的{{selectedFirstName}}专业</text></template>
              <template v-else> {{item.navName}} <text
                  class="titleTip">({{item.children.length||'0'}}个)</text></template>
            </view>
            <view class="thirdChildrenList">
              <view class="thirdChildrenItem" v-for="_item,_index in item.children" :key="_index"
                @click="handleThirdItemClick(_item)">
                <view class="thirdChildrenItemTitle"> {{_item.navName}}</view>
                <view class="thirdChildrenItemTags">
                  <view class="tagItem" v-if="_item.tagTimeDesc">{{_item.tagTimeDesc}}</view>
                  <view class="tagItem" v-if="_item.tagDesc">{{_item.tagDesc}}</view>
                </view>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
  </view>
</template>

<script>
import { reqZhituGetCareer } from "@/api/modules/company.js";
import { getNavigationTree, getSonNavigationTree } from "@/api/modules/career";

export default {
  name: "MajorFilterAI",
  props: {
    cateType: {
      type: String,
      default: "30",
    },
    specialStyle: {
      type: Object,
      default: () => {},
    },
    relevanceCareerId: {
      type: String,
      default: "1",
    },
    rectTop: {
      type: String,
      default: "0",
    },
  },
  data() {
    return {
      personId: uni.getStorageSync("person-id").slice(2) || undefined,
      positionTree: [], // 职业树
      recommend: [], // 推荐职业
      showRecommend: false,

      majorFirstList: [],
      secondPositionList: [],
      ThirdPositionList: [],
      selectedFirstId: "", //第一层选中的id
      selectedFirstName: "", //第一层选中的名字
      selectedFirstIndex: "", //第一层选中的下标
      scollFirstToView: "", //控制第一层筛选容器滚动的变量
      selectedSecondId: "", //第二层选中的id
      selectedSecondIndex: 0, //第二层选中的下标
      scrollSecondTop: 0, //第二层的滚动高度
      scollThirdToView: "", //控制第三层筛选容器滚动的变量
      distance: 0,
      isClickTab: false, //是否是点击滚动
      secondHeightArr: [], //第二层每一个专业的高度
      heightArr: [], //第三层每一个二级专业的高度
      tabActiveStyle: {
        "justify-content": "center",
        "align-items": "center",
        border: "4rpx solid #f75a3e",
        background: "linear-gradient(180deg, #ffece9 0%, #ffffff 100%)",
        "border-radius": "12rpx",
        "line-height": "98rpx",
      },
      scrollViewHeight: 0,
    };
  },
  methods: {
    //专科本科改变将index设为0
    currentIndexZero() {
      this.selectedFirstIndex = 0;
    },

    // 获取第一层
    reqgetNavigationTree() {
      getNavigationTree({})
        .then((res) => {
          if (res.code == 200) {
            this.majorFirstList = res.data || [];
            this.majorFirstList.unshift({
              navId: "-1",
              navName: "推荐",
            });
            console.log(
              "🚀 ~ 获取第一层 ~ this.majorFirstList:",
              this.majorFirstList
            );
            if (res.data.length) {
              this.selectedFirstId = res.data[0].navId;
              this.selectedFirstName = res.data[0].navName;
              this.reqgetSonNavigationTree(res.data[0].navId);
              this.scollFirstToView = ""; //需要先重置一下
              setTimeout(() => {
                this.scollFirstToView = "first-0"; //重置一下第三层滚动
              });
            }
          }
        })
        .catch((err) => {});
    },

    // 获取第二层
    reqgetSonNavigationTree(navId) {
      console.log("🚀 ~ 第二层起始参数 ~ navId:", navId);

      //如果是推荐就不请求
      if (navId == -1) return;
      //根据一级专业Id获取二级和三级列表，每次tab点击都会调用
      getSonNavigationTree({
        navId: navId,
        levelNum: 1,
      })
        .then((res) => {
          console.log("🚀 ~ . 获取第二层 ~ res:", res);
          if (res.code == 200) {
            this.secondPositionList = res.data[0].children || [];
            this.selectedSecondId = res.data[0].children[0].navId;
            this.cacSecondHeight();
            this.cacHeight();
            this.selectedSecondIndex = 0;
            this.isClickTab = true;
            setTimeout(() => {
              this.isClickTab = false;
            }, 300);
            this.scollThirdToView = ""; //需要先重置一下
            setTimeout(() => {
              this.scollThirdToView = "third-0"; //重置一下第三层滚动
              this.$set(
                this.secondPositionList[this.selectedSecondIndex],
                "isFixTitle",
                true
              );
            });
          }
        })
        .catch((err) => {});
    },

    handleFirstItemClick(index) {
      this.selectedFirstIndex = index;
      if (index == 0) {
        this.showRecommend = true;
        return;
      }
      this.selectedFirstId = "";
      const item = this.majorFirstList[index];
      console.log("🚀 ~ 点击了第一级 ~ item:", item);

      this.selectedFirstId = item.navId;
      this.selectedFirstName = item.navName;
      this.scollFirstToView = "first-" + index;
      this.reqgetSonNavigationTree(item.navId);
      // this.secondLevel(item.children);
    },
    handleSecondItemClick(item, index) {
      console.log("🚀 ~ handleSecondItemClick ~ item:", item, index);
      if (this.isClickTab) return;
      this.isClickTab = true;
      setTimeout(() => {
        this.isClickTab = false;
      }, 500);

      this.selectedSecondId = item.navId;
      this.selectedSecondIndex = index;
      this.scollThirdToView = "";
      this.$nextTick(() => {
        this.scollThirdToView = "third-" + index;
      });
    },
    handleThirdItemClick(_item) {
      this.$emit("clickItem", _item);
    },

    handleScroll(e) {
      if (this.isClickTab) return;
      this.$emit("closeBubble");
      let scrollTop = e.detail.scrollTop; //获取距离顶部的距离;
      //现在的item的高度
      const nowHeight = this.heightArr[this.selectedSecondIndex];
      //上一个的高度
      const preHiehgt = this.heightArr[this.selectedSecondIndex - 1];
      //处理第三层的滚动
      if (scrollTop > nowHeight) {
        if (this.secondPositionList.length > this.selectedSecondIndex + 1) {
          this.selectedSecondId =
            this.secondPositionList[this.selectedSecondIndex + 1].navId;
          this.selectedSecondIndex += 1;
          //如果滚动到顶部以后了，那就得固定一下title
          this.$set(
            this.secondPositionList[this.selectedSecondIndex],
            "isFixTitle",
            true
          );
        } else {
          console.log(
            "🚀 ~ file: majorFilterListAI.vue:217 ~ secondPositionList.length:",
            this.secondPositionList.length
          );
        }
      } else if (scrollTop < preHiehgt) {
        if (this.secondPositionList[this.selectedSecondIndex - 1]) {
          this.selectedSecondId =
            this.secondPositionList[this.selectedSecondIndex - 1].navId;
          this.selectedSecondIndex -= 1;
          this.$set(
            this.secondPositionList[this.selectedSecondIndex],
            "isFixTitle",
            true
          );
        }
      }
      //处理二级跟随滚动
      this.scrollSecondTop =
        this.secondHeightArr[this.selectedSecondIndex] -
        parseInt(this.specialStyle.height.slice(0, -2) / 2);
    },
    cacHeight() {
      this.$nextTick(() => {
        let list = [];
        let height = 0;
        const query = uni.createSelectorQuery().in(this);
        query.selectAll(".ThirdPositionItem").boundingClientRect();
        query.exec((res) => {
          res[0].forEach((item) => {
            height += parseInt(item.height);
            list.push(height);
            height += parseInt(100);
            list.push(height);
          });
          this.heightArr = list;
        });
      });
    },
    //计算二级的每个高度
    cacSecondHeight() {
      this.$nextTick(() => {
        let list = [];
        let height = 0;
        const query = uni.createSelectorQuery().in(this);
        query.selectAll(".SecondPositionItem").boundingClientRect();
        query.exec((res) => {
          res[0].forEach((item) => {
            height += parseInt(item.height);
            list.push(height);
          });
          this.secondHeightArr = list;
        });
      });
    },

    // 获取职业列表(数据写死固定的)
    zhituGetStartInfo() {
      this.isLoading = true;
      let params = {
        personId: this.relevanceCareerId,
      };
      reqZhituGetCareer(params)
        .then((res) => {
          console.log("🚀 ~ .推荐内容 ~ res:", res);
          this.isLoading = false;
          if (res.code == 200) {
            this.recommend = res.data.recommend;
            // this.positionTree = res.data.positionTree;
            // this.firstLevel(res.data.positionTree);
          } else {
            uni.showToast({
              title: res.status_desc,
              icon: "error",
            });
          }
        })
        .catch((err) => {
          this.isLoading = false;
        });
    },

    // firstLevel(data) {
    //   this.majorFirstList = data || [];
    //   this.majorFirstList.unshift({
    //     positionId: "-1",
    //     positionName: "推荐",
    //   });
    //   if (data.length > 0) {
    //     let obj = data[0];
    //     this.selectedFirstId = obj.positionId;
    //     this.selectedFirstName = obj.positionName;
    //     this.secondLevel(obj.children);
    //     this.scollFirstToView = ""; //需要先重置一下
    //     setTimeout(() => {
    //       this.scollFirstToView = "first-0"; //重置一下第三层滚动
    //     });
    //   }
    // },
    // secondLevel(data) {
    //   if (!data || data.length == 0) {
    //     return;
    //   }
    //   this.secondPositionList = data || [];
    //   let secondObj = data[0];
    //   this.selectedSecondId = secondObj.positionId;

    //   this.cacSecondHeight();
    //   this.cacHeight();
    //   this.selectedSecondIndex = 0;
    //   this.isClickTab = true;
    //   setTimeout(() => {
    //     this.isClickTab = false;
    //   }, 300);
    //   this.scollThirdToView = ""; //需要先重置一下
    //   setTimeout(() => {
    //     this.scollThirdToView = "third-0"; //重置一下第三层滚动
    //     this.$set(
    //       this.secondPositionList[this.selectedSecondIndex],
    //       "isFixTitle",
    //       true
    //     );
    //   });
    // },
  },

  created() {
    this.reqgetNavigationTree();
    this.zhituGetStartInfo();

    let height = 0;
    uni.getSystemInfo({
      success: function (res) {
        if (res.statusBarHeight == 20) {
          height = res.screenHeight - 246;
        } else {
          height = res.screenHeight - 328;
        }
      },
    });
    this.recommendHeight = height;
  },
  watch: {
    cateType(newValue, oldValue) {
      if (newValue) {
        this.reqgetNavigationTree();
        this.zhituGetStartInfo();
      }
    },
    rectTop(newValue, oldValue) {
      if (newValue) {
        let searchBottom = newValue;
        const { screenHeight } = uni.getSystemInfoSync();
        this.scrollViewHeight =
          screenHeight - searchBottom + 18 - uni.upx2px(10);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.wrapper {
  margin-top: 26rpx;
  width: 100vw;
  min-height: 400rpx;
  // overflow: hidden;
  .majorFilterContainer {
    .firstListContainer {
      // display: flex;
      height: 100rpx;
      // padding: 0 32rpx;
      width: 100vw;
      margin-bottom: 38rpx;
      // white-space: nowrap; /* 禁止换行，很重要 */
      // overflow-x: hidden; /* 显示滚动条 */
      // scroll-snap-type: x mandatory; /* 开启滚动吸附 */
      .firstListItem {
        display: inline-flex;
        justify-content: center;
        align-items: center;
        scroll-snap-align: center; /* 设置吸附位置 */
        height: 100rpx;
        padding: 0 28rpx;
        margin-right: 16rpx;
        border-radius: 12rpx;
        border: 2rpx solid #e4e5f5;
        background: linear-gradient(180deg, #ebf5fe 0%, #ffffff 100%);
        &.selectedFirst {
          border: 4rpx solid #f75a3e;
          background: linear-gradient(180deg, #ffece9 0%, #ffffff 100%);
        }
        &:last-of-type {
          margin-right: 0rpx;
        }
      }
    }
  }

  .recommendArea {
    display: flex;
    flex-wrap: wrap;
    height: calc(100vh - 582rpx);
    .recommendItem {
      width: 30%;
      height: 200rpx;
      display: inline-flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      margin: 10rpx;
    }
    .recommendImgArea {
      width: 124rpx;
      height: 124rpx;
      border-radius: 70rpx;
      background-color: #ebebeb;
      display: flex;
      justify-content: center;
      align-items: center;
      overflow: hidden;
      padding-top: 12rpx;
    }
    .recommendImg {
      width: 100%;
      height: 100%;
    }
    .recommendText {
      align-items: center;
      color: #222222;
      margin-top: 14rpx;
    }
  }
  .mainListContainer {
    display: flex;
    // justify-content: start;
    .secondPositionList {
      // display: flex;
      // flex-direction: column;

      height: calc(100vh - 328px);
      background-color: #f4f6f8;
      .SecondPositionItem {
        display: flex;
        // justify-content: center;
        align-items: center;
        // width: 212rpx;
        padding-left: 32rpx;
        height: 100rpx;
        background: #f4f6f8;
        color: #666666;
        span {
          // display: inline-flex;
          // justify-content: center;
          // align-items: center;
          text-align: left;
          max-width: 160rpx;
          font-size: 28rpx;
          // overflow: hidden;
          // white-space: nowrap;
          // text-overflow: ellipsis;
        }
        .hotSecondPosition {
          display: inline-flex;
          justify-content: flex-start;
          align-items: center;
          img {
            width: 28rpx;
            height: 36rpx;
            margin-right: 14rpx;
          }
        }
      }
      .selectedSecond {
        position: relative;
        background: #ffffff;
        font-weight: bold;
        color: #222222;
        &::after {
          content: "";
          position: absolute;
          bottom: -30rpx;
          right: 0rpx;
          height: 30rpx;
          width: 30rpx;
          background-image: url($img-base + "career/positionDictionary/radiuBorder.png");
          background-repeat: no-repeat;
          background-size: 100% 100%;
        }
        &::before {
          content: "";
          position: absolute;
          top: -30rpx;
          right: 0rpx;
          height: 30rpx;
          width: 30rpx;
          background-image: url($img-base + "career/positionDictionary/topRadiuBorder.png");
          background-repeat: no-repeat;
          background-size: 100% 100%;
        }
      }
    }
    .thirdPositionList {
      position: relative;
      height: calc(100vh - 285px);
      background-color: white;
      margin-left: -2rpx;
      .ThirdPositionItem {
        display: flex;
        flex-direction: column;
        border-bottom: 10rpx solid #f4f6f7;
        &:last-of-type {
          overflow: hidden;
          border-bottom: none;
          padding-bottom: 100rpx;
        }
        .thirdTitle {
          display: flex;
          align-items: center;
          width: 538rpx;
          height: 100rpx;
          padding: 0rpx 32rpx;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
          .titleTip {
            font-size: 26rpx;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #888888;
            line-height: 30rpx;
            padding-left: 16rpx;
          }
        }
        .fixedTitle {
          position: sticky;
          top: 0;
          z-index: 2;
          background-color: white;
        }
        .thirdChildrenList {
          display: flex;
          flex-direction: column;
          .thirdChildrenItem {
            display: flex;
            flex-direction: column;
            // width: 538rpx;
            // min-height: 124rpx;

            padding: 24rpx 0;
            margin: 0 32rpx;
            border-bottom: 1.2rpx solid #f5f5f5;
            .thirdChildrenItemTitle {
              font-size: 28rpx;
              font-family: PingFangSC;
              font-weight: bold;
              color: #222222;
              line-height: 30rpx;
              // margin-bottom: 16rpx;
            }
            .thirdChildrenItemTags {
              display: flex;
              .tagItem {
                display: flex;
                align-items: center;
                height: 30rpx;
                // line-height: 28rpx;
                font-size: 20rpx;
                padding: 0 6rpx;
                background: rgba(255, 119, 49, 0.05);
                border-radius: 6rpx;
                border: 1rpx solid #ff836c;
                color: #fa7259;
                margin-right: 16rpx;
              }
            }
          }
        }
      }
    }
  }
}
.u-tab-item {
  border: none;
  background: #f5f5f5;
}
</style>